package tongwentongshu.com.app.presenter;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.AMap;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.district.DistrictItem;
import com.huawei.android.pushagent.PushManager;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendAllowType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import tencent.tls.platform.TLSLoginHelper;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.activityim.UserInfo;
import tongwentongshu.com.app.bean.BookListBean;
import tongwentongshu.com.app.bean.LoginUser;
import tongwentongshu.com.app.bean.MessageReadBean;
import tongwentongshu.com.app.bean.PioBean;
import tongwentongshu.com.app.contract.MapMainContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.db.DataKeeper;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.update.UpdateFractory;
import tongwentongshu.com.app.utils.PushUtil;
import tongwentongshu.com.app.utils.SpUtils;

/**
 * Created by XiongBin on 2017/6/26.
 */

public class MapMainPresenter implements MapMainContract.Presenter {
    private MapMainContract.View mapmain;
    private Context mContext;
    // 当前行政区划
    private DistrictItem currentDistrictItem = null;
    List<DistrictItem> subDistrictList = null;
    List<DistrictItem> allClusterItems = new ArrayList<DistrictItem>();
    // 是否已经初始化
    private boolean isInit = false;
    //便利加载数据id
    private int index = -1;

    private Map<String, String> map;

    public MapMainPresenter(MapMainContract.View mapmain) {
        this.mapmain = mapmain;
    }

    @Override
    public void initMap(AMap aMap, Context mContext) {
        this.mContext = mContext;
        if (aMap != null) {
            UiSettings mUiSettings = aMap.getUiSettings();
//            setMapCustomStyleFile(aMap, mContext);
//            mUiSettings.setCompassEnabled(true);//设置地图默认的指南针是否显示
            mUiSettings.setMyLocationButtonEnabled(true); // 是否显示默认的定位按钮
            mUiSettings.setScrollGesturesEnabled(true);//设置地图是否可以手势滑动
            mUiSettings.setZoomGesturesEnabled(true);//设置地图是否可以手势缩放大小
            mUiSettings.setTiltGesturesEnabled(false);//设置地图是否可以倾斜
            mUiSettings.setRotateGesturesEnabled(false);//设置地图是否可以旋转
            mUiSettings.setCompassEnabled(false);
            mUiSettings.setZoomControlsEnabled(false);
            aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
            aMap.setTrafficEnabled(false);// 显示实时交通状况
            aMap.showBuildings(true);// 显示3D 楼块
            aMap.showMapText(true);// 显示底图文字
            aMap.setMinZoomLevel(10);//设置最小缩放限制
//            aMap.setMaxZoomLevel(18);//设置最大缩放限制
            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.strokeColor(mContext.getResources().getColor(R.color.transparent));//设置定位蓝点精度圆圈的边框颜色的方法。
            myLocationStyle.radiusFillColor(mContext.getResources().getColor(R.color.transparent));//设置定位蓝点精度圆圈的填充颜色的方法。
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
            aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
            aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        }
    }

    /**
     * 初始化标记点
     */
    @Override
    public void intiBooks(Activity act) {
        mContext = act;
//        AlertUtils.showLoding(mContext);
        map = new ArrayMap<>();
        UpdateFractory.getBuild()
                .name("PioCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<PioBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(PioBean poiBean, String msg) {
                        mapmain.onSuccess(poiBean);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
//
    }

    @Override
    public void intiBooksList(Activity act, String aoiid, String type) {
        AlertUtils.showLoding(act);
        mContext = act;
        map = new ArrayMap<>();
        map.put("aoiid", aoiid);
        map.put("pagesize", "50");
        if (!TextUtils.isEmpty(type))
            map.put("status", type);
        UpdateFractory.getBuild()
                .name("BookListCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<BookListBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(BookListBean bookListBean, String msg) {
                        mapmain.onSuccess(bookListBean);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        AlertUtils.disMissLoding();
                    }
                });
    }

    @Override
    public void intiMessage(Activity act) {
        mContext = act;
        map = new ArrayMap<>();
        map.put("token", Cache.getToken());
        UpdateFractory.getBuild()
                .name("MessageReadCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<MessageReadBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(MessageReadBean bean, String msg) {
                        mapmain.onSuccess(bean);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    @Override
    public void login(final Context mContext, String token) {
        String phone = SpUtils.getString(mContext, Cache.USER_NAME, "-1");
        String password = SpUtils.getString(mContext, Cache.USER_PASSWORD, "-1");
        if (TextUtils.isEmpty(phone) || phone.equals("-1") || TextUtils.isEmpty(password))
            return;
        map = new ArrayMap<>();
        map.put("mobile", phone);
        map.put("password", password);
        map.put("phonetype", "0");
        map.put("device_tokens", token);
        map.put("longitude", SpUtils.getString(mContext, Cache.LON, ""));
        map.put("latitude", SpUtils.getString(mContext, Cache.LAT, ""));
        map.put("mapaddress", SpUtils.getString(mContext, Cache.ADDRESS, ""));
        UpdateFractory.getBuild()
                .name("LoginCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<LoginUser>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        SpUtils.setString(mContext, Cache.USER_PASSWORD, "");
                    }

                    @Override
                    public void onSuccess(LoginUser login, String msg) {
                        if (null != login) {
                            login.setLogin(true);
                            DataKeeper.keepSerializable(App.getContext(), login);
                            Cache.setUser();
                            mapmain.onLoginSuccess();
                            UserInfo.getInstance().setUserSig(login.getData().getSig());
//                            if (!TextUtils.isEmpty(UserInfo.getInstance().getId()))
                            initMSG(mContext, login);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    void initMSG(Context mContext, final LoginUser login) {
        TLSLoginHelper loginHelper = TLSLoginHelper.getInstance().init(mContext,
                1400036219, 14371, SpUtils.getString(mContext, Cache.USER_NAME, ""));

//        loginHelper.setTimeOut(TLSConfiguration.TIMEOUT);
//        loginHelper.setLocalId(TLSConfiguration.LANGUAGE_CODE);
        loginHelper.setTestHost("", true);                   // 走sso
        final String identify = SpUtils.getString(mContext, Cache.USER_NAME, "");
        final String userSig = login.getData().getSig();
        TIMManager.getInstance().login(identify, userSig, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.d("shiqiang", "login failed. code: " + code + " errmsg: " + desc);
                System.out.println("wocBUGkle");
            }

            @Override
            public void onSuccess() {
                Log.d("shiqiang", "login succ");
                System.out.println("wochenggongkle");


                UserInfo.getInstance().setId(identify);
                UserInfo.getInstance().setUserSig(userSig);

                setAddType(login);

            }
        });
    }

    private void setAddType(LoginUser login) {
        //设置自己的好友验证方式为b不需要验证
        TIMFriendshipManager.ModifyUserProfileParam param = new TIMFriendshipManager.ModifyUserProfileParam();
        param.setAllowType(TIMFriendAllowType.TIM_FRIEND_ALLOW_ANY);
        param.setNickname(login.getData().getNickname());
        param.setFaceUrl(login.getData().getHeadurl());
        TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.e("LoginPresenter", "modifyProfile failed: " + code + " desc" + desc);
            }

            @Override
            public void onSuccess() {
                Log.e("TIMFriendshipManager", "设置昵称头像成功！");
            }
        });
        LoginBusiness.loginIm(SpUtils.getString(mContext, Cache.USER_NAME, ""), UserInfo.getInstance().getUserSig(), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess() {
                registerPush();
            }
        });
    }


    public void registerPush() {
//        //初始化程序后台后消息推送
//        PushUtil.getInstance();
//        //初始化消息监听
//        MessageEvent.getInstance();
        String vendor = Build.MANUFACTURER;
        Log.e("vendor", vendor.toLowerCase(Locale.ENGLISH));
        if (vendor.toLowerCase(Locale.ENGLISH).contains("xiaomi") && shouldMiInit()) {
            //注册小米推送服务
            MiPushClient.registerPush(mContext, "2882303761517604448", "5311760450448");
        } else if (vendor.toLowerCase(Locale.ENGLISH).contains("huawei")) {

            //请求华为推送设备token
            PushManager.requestToken(mContext);
        }
    }

    /**
     * 判断小米推送是否已经初始化
     */
    private boolean shouldMiInit() {
        ActivityManager am = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = mContext.getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

}
